package com.airconditioner.sales.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.airconditioner.sales.R;
import com.airconditioner.sales.appliaction.MyApplication;
import com.airconditioner.sales.model.UserInfo;
import com.airconditioner.sales.util.ShareP;
import com.airconditioner.sales.weixin.Constants;
import com.alibaba.fastjson.JSON;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.x;

/**
 * 作者：shuizi_wade on 2017/1/16 13:47
 * 邮箱：674618016@qq.com
 */
@ContentView(R.layout.activity_wxlogin)
public class WxLoginActivity extends BaseActivity {
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                String wxToken = (String) msg.obj;
                getAccess_token(wxToken);
            }
        }
    };
    private SendAuth.Req req;
    private static final String WEIXIN_SCOPE = "snsapi_userinfo";
    private static final String WEIXIN_STATE = "login_state";
    private IWXAPI api;

    @Override
    public void init() {
        super.init();
        MyApplication.getInstance().setWxHandler(handler);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);
        title_iv_back.setImageResource(R.mipmap.titlebar_back_white);
        title_tv_title.setText(R.string.wx_login);
        title_tv_title.setTextColor(getResources().getColor(R.color.white_color));
        title_iv_back.setBackgroundColor(getResources().getColor(R.color.toolbar_color));
        title_relate_layout.setBackgroundColor(getResources().getColor(R.color.toolbar_color));
        findViewById(R.id.layout_wx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WxLoginActivity.this, RegisterActivity.class));
//                sendAuth();
            }
        });
    }

    private void sendAuth() {
        req = new SendAuth.Req();
        req.scope = WEIXIN_SCOPE;
        req.state = WEIXIN_STATE;
        api.sendReq(req);
    }

    @Override
    public void success(String result, String type) {
        super.success(result, type);
        if (type.equals("access_token")) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String openid = jsonObject.getString("openid").toString().trim();
                String access_token = jsonObject.getString("access_token").toString().trim();
                getUserMesg(access_token, openid);
            } catch (JSONException e) {
                e.printStackTrace();
                senToa(e.getMessage());
            }
        } else if (type.equals("userMsg")) {
            UserInfo userInfo = JSON.parseObject(result.toString(), UserInfo.class);
            ShareP.saveUserId(context, userInfo.getUnionid());
            ShareP.saveUserName(context, userInfo.getNickname());
            ShareP.saveUserPic(context, userInfo.getHeadimgurl());
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("userInfo", userInfo);
            intent.putExtras(bundle);
            intent.setClass(WxLoginActivity.this, RegisterActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + Constants.APP_ID
                + "&secret="
                + Constants.APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        http(path, "access_token");
    }


    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        System.out.println("url:" + path);
        http(path, "userMsg");
    }
}
